package cn.openea.perpartner.common.rabbit.task;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import cn.openea.perpartner.common.core.utils.PageUtils;
import cn.openea.perpartner.common.core.utils.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import java.lang.reflect.Method;


/**
 * @author Weird077
 * @description TODO
 * @date 2022-07-17 0:37
 */
@Component
public class AsyncTask {
    @Async
    public ListenableFuture<Object> asyncInvoke(JSONObject formData) throws Exception {
        //bean名称，对应service类
        String beanName = formData.getString("beanName");
        //方法名
        String methodName = formData.getString("methodName");
        methodName = StringUtils.isNotEmpty(methodName) ? methodName : "run";
        //设置分页
        if (formData.containsKey("pageNum") || formData.containsKey("pageSize")) {
            PageUtils.startMinRestPage(formData);
        }
        //从Spring上下文获取bean
        Object bean = SpringUtil.getBean(beanName);
        //获取类实例对象
        Class<?> clazz = bean.getClass();
        //获取方法
        Method method = clazz.getDeclaredMethod(methodName, JSONObject.class);
        //执行方法
        Object invoke = method.invoke(bean, formData);
        return new AsyncResult(invoke);
    }
}
